package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.study.entity.StudentAccount;
import com.xmy.study.entity.SysSet;
import com.xmy.study.entity.response.Course;
import com.xmy.study.entity.response.LoginResult;
import com.xmy.study.feign.IStudentFeignClient;
import com.xmy.study.respons.ProfileResult;
import com.xmy.study.service.ISysSetService;
import com.xmy.study.util.Code;
import com.xmy.study.util.Result;
import com.xmy.study.util.ResultCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/web/login")
public class LoginController {

    //为了后来系统的兼容性，应该所有对象都是以json的方式进行保存
    @Autowired //如果给redis中保存数据会使用默认的序列化机制，导致redis中保存的对象不可视
            RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    ISysSetService iSysSetService;

    @Autowired
    IStudentFeignClient iStudentFeignClient;


    @GetMapping("logOut")
    public Result logOut() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return new Result(Code.OK,"","退出成功");
    }

    @PostMapping()
    public Result login(@RequestBody Map<String,String> reMap){

        //构造登录令牌
        try {
            String username = reMap.get("username").trim();
            String password = reMap.get("password").trim();
            //password = new Md5Hash(password,username,3).toString();
//            System.out.println("password:"+password);
            UsernamePasswordToken upToken = new UsernamePasswordToken(username,password);
            Subject subject = SecurityUtils.getSubject();
            //2.调用subject进行登录
            subject.login(upToken);//获取session
            String sid = (String) subject.getSession().getId();
            LoginResult loginResult = new LoginResult();

            //1.subject获取所有的安全数据集合
            StudentAccount studentAccount = null;
            ProfileResult profileResult = null;
            PrincipalCollection principals = subject.getPrincipals();
            if(principals != null && !principals.isEmpty()){
                //2.获取安全数据
                profileResult = (ProfileResult) principals.getPrimaryPrincipal();
                studentAccount =(StudentAccount) profileResult.getStudentAccount();

                SysSet sysSetInfo = iSysSetService.getById(10000L);
                if (sysSetInfo.getIsMaintain().equals(1)){
                    return new Result(Code.ERROR,loginResult,sysSetInfo.getLoginMsg());
                }
                //学生帐号
                if (studentAccount.getStatus().equals(0)){
                    //帐号补禁用
                    return new Result(Code.ERROR,loginResult,"帐号不用使用，请与老师联系");
                }

                if (studentAccount.getAccountType().equals(1)){
                    if (sysSetInfo !=null && studentAccount.getStatus().equals(1)){
                        //学生正式帐号
                        if (sysSetInfo.getAllowStudentLogin().equals(0)){
                            return new Result(Code.ERROR,loginResult,sysSetInfo.getLoginMsg());
                        }
                    }else if (sysSetInfo !=null && studentAccount.getStatus().equals(2)){
                        //试用帐号
                        if (sysSetInfo.getAllowTryStudentLogin().equals(0)){
                            return new Result(Code.ERROR,loginResult,sysSetInfo.getLoginMsg());
                        }
                        if (studentAccount.getTryOutEndDate()!=null && studentAccount.getTryOutEndDate().isBefore(LocalDate.now())){
                            return new Result(Code.ERROR,loginResult,"试用期已过，不能登陆");
                        }
                    }
                }
            }
            loginResult.setToken(sid);
            studentAccount.setPwd("");
            loginResult.setStudentInfo(studentAccount);

            QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();
            courseQueryWrapper.eq("student_id", studentAccount.getStudentId());
            courseQueryWrapper.orderByDesc("id");
            courseQueryWrapper.eq("deleted", 0);
            courseQueryWrapper.ne("status", 2);
            courseQueryWrapper.groupBy("subjects_id");
            List<Course> courseList = iSysSetService.studentCourse(courseQueryWrapper);
            ArrayList<Integer> subjectsIdArr = new ArrayList<>();
            if (!courseList.isEmpty()) {
                for (Course course : courseList) {
                    subjectsIdArr.add(Math.toIntExact(course.getSubjectsId()));
                }
            }
//            subjectsIdArr.add(3);//测试完关掉
            loginResult.setSubjectsIdStr(subjectsIdArr);

            //设置redis_key 唯一设备登录
            String userRedisKey = "usershiroifredis"+username;
            //写入redis 唯一设备登录
            redisTemplate.opsForValue().set(userRedisKey, sid,3, TimeUnit.HOURS);
//            System.out.println("loginsid:"+sid);
            return new Result(Code.OK,loginResult,"");

        }catch (Exception e) {
            //return new Result(Code.ERROR,e.getMessage());
            //return new Result(Code.OK,data);
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }
    }
}
